package yt.kpool.activity.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import yt.kpool.R;
import yt.kpool.base.BaseApplication;
import yt.kpool.bean.LineChartTestBean;
import yt.kpool.bean.PoolCoinDetailsBean;
import yt.kpool.bean.PowCoinChartBean;
import yt.kpool.bean.PowCoinDetailBean;
import yt.kpool.network.HttpUtils;
import yt.kpool.network.MyGson;
import yt.kpool.network.NetHelperNew;
import yt.kpool.util.DynamicLineChartDManager;
import yt.kpool.util.DynamicLineChartDetailManager;

import yt.kpool.util.NetWorkUtil;
import yt.kpool.util.SPUtil;
import yt.kpool.util.ToastUtil;
import yt.kpool.util.Util;
import yt.kpool.util.imageUtil.GlideUtil;
import yt.kpool.view.CircularProgressViews;
import yt.kpool.view.dialog.LoadingDialog;

/**
 * 主页列表详情
 */
public class HomeSecondDetailAc extends AppCompatActivity {
    @BindView(R.id.circleProgressBar)
    CircularProgressViews circleProgressBar;
    @BindView(R.id.circleProgressBar2)
    CircularProgressViews circleProgressBar2;
    @BindView(R.id.dynamic_chart2)
    LineChart mChart2;
    @BindView(R.id.tv_remark)
    TextView tv_remark;
    @BindView(R.id.tv_remarks)
    TextView tv_remarks;
    @BindView(R.id.tv_more)
    TextView tv_more;
    @BindView(R.id.iv_more)
    ImageView iv_more;
    @BindView(R.id.tv_TotalSupply)
    TextView tv_TotalSupply;
    @BindView(R.id.tv_RemainMinable)
    TextView tv_RemainMinable;
    @BindView(R.id.tv_CirculatingSupply)
    TextView tv_CirculatingSupply;
    @BindView(R.id.tv_tv_CirculatingSupplylv)
    TextView tv_tv_CirculatingSupplylv;
    @BindView(R.id.tv_Volume24h)
    TextView tv_Volume24h;
    @BindView(R.id.tv_hslv)
    TextView tv_hslv;
    @BindView(R.id.tv_MarketCap)
    TextView tv_MarketCap;
    @BindView(R.id.tv_qusz)
    TextView tv_qusz;
    @BindView(R.id.edit)
    EditText edit;
    @BindView(R.id.tv_ThroughputUnit)
    TextView tv_ThroughputUnit;
    @BindView(R.id.tv_Throughput)
    TextView tv_Throughput;
    @BindView(R.id.tv_rmoney)
    TextView tv_rmoney;
    @BindView(R.id.tv_ThroughputU)
    TextView tv_ThroughputU;
    @BindView(R.id.tv_money)
    TextView tv_money;
    @BindView(R.id.tv_moneyy)
    TextView tv_moneyy;
    @BindView(R.id.tv_Algorithm)
    TextView tv_Algorithm;
    @BindView(R.id.tv_BlockHeight)
    TextView tv_BlockHeight;
    @BindView(R.id.tv_Difficulty)
    TextView tv_Difficulty;
    @BindView(R.id.tv_PriceTrend)
    ImageView iv_PriceTrend;
    @BindView(R.id.iv_icon)
    ImageView iv_icon;
    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_u)
    TextView tv_u;
    @BindView(R.id.tv_moneys)
    TextView tv_moneys;
    @BindView(R.id.mywitcher)
    Switch mywitcher;
    @BindView(R.id.tv_minue)
    TextView tv_minue;
    @BindView(R.id.tv_day)
    TextView tv_day;
    @BindView(R.id.tv_title1)
    TextView tv_title1;
    @BindView(R.id.tv_title2)
    TextView tv_title2;
    private boolean b=true;
    private List<Integer> list = new ArrayList<>(); //数据集合
    private List<String> names = new ArrayList<>(); //折线名字集合
    private List<Integer> colour = new ArrayList<>();//折线颜色集合
    private DynamicLineChartDManager dynamicLineChartManager;
    private DynamicLineChartDetailManager dynamicLineChartManager2;
    private LoadingDialog loadingDialog;
    private SPUtil spUtil;
    private int kind=0;
    private String day="30";
    private PowCoinDetailBean powCoinDetailBean;
    private  String code="";

    public static void start(Context mactivity, String ID) {
        Intent intent = new Intent(mactivity, HomeSecondDetailAc.class);
        intent.putExtra("ID", ID);
        mactivity.startActivity(intent);
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homeseconddetail);
        ButterKnife.bind(this);
        init();
        getData(getIntent().getStringExtra("ID"));


    }



    private void init()
    {

        spUtil = new SPUtil(HomeSecondDetailAc.this, "fileName");
        loadingDialog = new LoadingDialog(this, 0);

        initSwitcher();

        edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if(powCoinDetailBean!=null)
                {
                    if(charSequence.toString().equals(""))
                    {
                        if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1) {

                            //人民币币价
                            tv_Throughput.setText("0");
                            tv_rmoney.setText("≈ ￥ 0");

                        } else if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2) {
                            //美元
                            tv_Throughput.setText("0");
                            tv_rmoney.setText("≈ $ 0");
                        }

                        return;
                    }

                    if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1) {


                        BigDecimal bi1 = new BigDecimal(powCoinDetailBean.getData().getPrice());

                        BigDecimal bi2 = new BigDecimal(BaseApplication.Exchange + "");
                        double s = bi1.multiply(bi2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                        String st=Util.NMultiplication(Double.valueOf(charSequence.toString())+"",powCoinDetailBean.getData().getEstimatedProfit()+"");
                        //人民币币价
                        tv_Throughput.setText(st);
                        tv_rmoney.setText("≈ ￥ "+Util.Multiplication(s+"",st));


                    } else if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2) {
                        String st=Util.NMultiplication(Double.valueOf(charSequence.toString())+"",powCoinDetailBean.getData().getEstimatedProfit()+"");
                        //美元
                        tv_Throughput.setText(st);
                        tv_rmoney.setText("≈ $ "+Util.Multiplication(powCoinDetailBean.getData().getPrice()+"",st));

//                            tv_Throughput.setText(dataBean.getThroughput() + " " + dataBean.getCode() + "≈$" + t);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1) {
            kind=1;
            tv_moneys.setText("CNY");

        } else if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2) {
            kind=2;
            tv_moneys.setText("USD");
        }


    }
    private void initSwitcher() {
        mywitcher.setChecked(true);
        tv_day.setTextColor(getResources().getColor(R.color.system_color));
        tv_minue.setTextColor(getResources().getColor(R.color.white));
        mywitcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    //选中状态 可以做一些操作
                    //未选中状态 可以做一些操作
                    tv_day.setTextColor(getResources().getColor(R.color.system_color));
                    tv_minue.setTextColor(getResources().getColor(R.color.white));
                    day="30";
                    getPowChartDate(code,day,1);
                } else {
                    day="7";
                    tv_minue.setTextColor(getResources().getColor(R.color.system_color));
                    tv_day.setTextColor(getResources().getColor(R.color.white));
                    getPowChartDate(code,day,1);
                }
            }
        });

    }
    /**
     * 获取详情的网络数据
     */
    private void getData(String currencyId)
    {

        if(NetWorkUtil.checkNet(HomeSecondDetailAc.this))
        {
            loadingDialog.show();
            NetHelperNew.PowCoinDetails(currencyId,new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {
                    Log.i("-->", "pow详情：" + data);

                    powCoinDetailBean = MyGson.getInstance().fromJson(data, PowCoinDetailBean.class);

                    if (powCoinDetailBean.getType() == 1) {
                        String Code=" "+powCoinDetailBean.getData().getCode().toUpperCase();
                        code=powCoinDetailBean.getData().getCode();
                        GlideUtil.loadImage(HomeSecondDetailAc.this, NetHelperNew.URL + powCoinDetailBean.getData().getIcon(), iv_icon, R.mipmap.failimage, R.mipmap.failimage);
                        tv_name.setText(powCoinDetailBean.getData().getCode().toUpperCase());
                        tv_remark.setText(powCoinDetailBean.getData().getRemark());
                        tv_remarks.setText(powCoinDetailBean.getData().getRemark());
                        tv_title1.setText(powCoinDetailBean.getData().getCode().toUpperCase()+" 全网算力");
                        tv_title2.setText(powCoinDetailBean.getData().getCode().toUpperCase()+" 价格走势");

                        if(powCoinDetailBean.getData().getTotalSupply()==-1)
                        {
                            tv_TotalSupply.setText("∞");
                            tv_RemainMinable.setText("0"+Code);
                            tv_tv_CirculatingSupplylv.setText("");

                        }
                        else
                        {
                            tv_TotalSupply.setText(Util.FormatTosepara(powCoinDetailBean.getData().getTotalSupply())+Code);
                            tv_RemainMinable.setText(Util.FormatTosepara(powCoinDetailBean.getData().getRemainMinable())+Code);
                            String sss=powCoinDetailBean.getData().getCirculatingSupply()/powCoinDetailBean.getData().getTotalSupply()*100+"";
                            tv_tv_CirculatingSupplylv.setText(Util.GetTNumber(sss)+"%");
                            int hh=Double.valueOf(sss).intValue();
                            circleProgressBar.update(Double.valueOf(hh*3.6).intValue(),"");
                        }

                        tv_CirculatingSupply.setText(Util.FormatTosepara(powCoinDetailBean.getData().getCirculatingSupply())+Code);

                        if(powCoinDetailBean.getData().getMarketCap()==0)
                        {
                            tv_hslv.setText("0%");
                            circleProgressBar2.update(0,"");
                        }
                        else
                        {  String ss=powCoinDetailBean.getData().getVolume24h()/powCoinDetailBean.getData().getMarketCap()*100+"";
                            tv_hslv.setText(Util.GetTNumber(ss)+"%");
                            int h=Double.valueOf(ss).intValue();
                            circleProgressBar2.update(Double.valueOf(h*3.6).intValue(),"");
                        }


                        tv_qusz.setText("");//占全球总市值%
                        tv_BlockHeight.setText(powCoinDetailBean.getData().getBlockHeight()+"");
                        tv_Difficulty.setText(Util.FormatHashrate(powCoinDetailBean.getData().getDifficulty()));
                        tv_moneyy.setText("" +Util.GetTNumber(powCoinDetailBean.getData().getPriceChange24h()+"")+"%");
                        tv_Throughput.setText(Util.GetNumber(powCoinDetailBean.getData().getEstimatedProfit()+""));
                        edit.setText("1");
                        tv_Algorithm.setText(powCoinDetailBean.getData().getAlgorithm());
                        tv_ThroughputUnit.setText(powCoinDetailBean.getData().getProfitPerHash());
                        tv_ThroughputU.setText(Code);
                        if(powCoinDetailBean.getData().getPriceChange24h()>0)
                        {
                            iv_PriceTrend.setImageResource(R.mipmap.shangzhang);
                            tv_moneyy.setTextColor(Color.parseColor("#2b9054"));
                        }
                        else if(powCoinDetailBean.getData().getPriceChange24h()<0)
                        {
                            iv_PriceTrend.setImageResource(R.mipmap.xiadie);
                            tv_moneyy.setTextColor(Color.parseColor("#ff003c"));
                        }
                        double t = powCoinDetailBean.getData().getEstimatedProfit() * powCoinDetailBean.getData().getPrice();//美元的日理论收益
                        if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 1) {
                            BigDecimal bi1 = new BigDecimal(powCoinDetailBean.getData().getPrice());

                            BigDecimal bi2 = new BigDecimal(BaseApplication.Exchange + "");
                            double s = bi1.multiply(bi2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                            BigDecimal bi3 = new BigDecimal(t);
                            double f = bi3.multiply(bi2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();

                            //人民币币价
                            tv_money.setText("￥" + s+" ");
                            tv_rmoney.setText("≈ ￥ "+Util.Multiplication(s+"",powCoinDetailBean.getData().getEstimatedProfit()+""));
                            String s1=Util.Multiplication(powCoinDetailBean.getData().getVolume24h()+"",BaseApplication.Exchange+"");
                            tv_Volume24h.setText("￥ "+Util.FormatTosepara(Double.valueOf(s1)));
                            String s2=Util.Multiplication(powCoinDetailBean.getData().getMarketCap()+"",BaseApplication.Exchange+"");
                            tv_MarketCap.setText("￥ "+Util.FormatTosepara(Double.valueOf(s2)));

                        } else if (spUtil.getInt(BaseApplication.MONEYKIND, 0) == 2) {
                            //美元
                            tv_money.setText("$" + Util.GetTNumber(powCoinDetailBean.getData().getPrice()+""));
                            tv_rmoney.setText("≈ $ "+Util.Multiplication(powCoinDetailBean.getData().getPrice()+"",powCoinDetailBean.getData().getEstimatedProfit()+""));
                            tv_Volume24h.setText("$ "+Util.FormatTosepara(powCoinDetailBean.getData().getVolume24h()));
                            tv_MarketCap.setText("$ "+Util.FormatTosepara(powCoinDetailBean.getData().getMarketCap()));
                        }

                        getPowChartDate(code,day,0);


                    }
                    else
                    {
                        loadingDialog.dismiss();
                    }
                }


                @Override
                public void onError(String msg) {
                    super.onError(msg);
                    loadingDialog.dismiss();
                    ToastUtil.showToast(HomeSecondDetailAc.this, msg);
                }
            });
        }
        else
        {

            ToastUtil.showToast(HomeSecondDetailAc.this,getResources().getString(R.string.internet_error));
        }


    }
    @OnClick({ R.id.ly_more,R.id.title_left})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ly_more:
                if(b)
                {
                    tv_more.setText("收起");
                    iv_more.setImageResource(R.mipmap.xiangss);
                    tv_remark.setVisibility(View.GONE);
                    tv_remarks.setVisibility(View.VISIBLE);
                    b=false;
                }
                else
                {
                    tv_more.setText("查看更多");
                    iv_more.setImageResource(R.mipmap.xiangxx);
                    tv_remark.setVisibility(View.VISIBLE);
                    tv_remarks.setVisibility(View.GONE);
                    b=true;
                }

                break;

            case R.id.title_left:
                finish();
                break;

        }
    }
    /**
     * 获取图表数据
     * @param Code
     * @param Day
     */
    private void  getPowChartDate(String Code,String Day,final int k)
    {



        if(NetWorkUtil.checkNet(HomeSecondDetailAc.this))
        {
            if(k==1)
            {
                loadingDialog.show();
            }

            NetHelperNew.PowCoinChart(Code, Day, new HttpUtils.HttpCallback() {
                @Override
                public void onSuccess(String data) {

                    loadingDialog.dismiss();

                    PowCoinChartBean powCoinChartBean = MyGson.getInstance().fromJson(data, PowCoinChartBean.class);
                    if(powCoinChartBean.getType()==1)
                    {

                        float max = 0;
                        float maxx = 0;
                        List<LineChartTestBean> list=new ArrayList<>();
                        List<PowCoinChartBean.DataBean.ChartDataBean> listt =powCoinChartBean.getData().getChartData();
                        String strU="",strUU="";
                        for (int i=0;i<listt.size();i++)
                        {
                            strU=listt.get(i).getHashrateUnit();
                            String date[]=listt.get(i).getCreatedTime().split(" ");
                            int m=date[0].length();
                            String time=date[0].substring(5,m);
                            String money="";
                            if(kind==1)
                            {
                                money=Util.Multiplication(listt.get(i).getPrice()+"",powCoinChartBean.getData().getExchange()+"");
                                strUU="￥";
                            }
                            else
                            {
                                strUU="$";
                                money=Util.GetTNumber(listt.get(i).getPrice()+"");
                            }

                            list.add(new LineChartTestBean(time, Float.valueOf(listt.get(i).getHashrate()+""),Float.valueOf(money)));
                        }



                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getFilingNumber() > max) {
                                max = list.get(i).getFilingNumber();
                            }
                            if (list.get(i).getTNumber() > maxx) {
                                maxx = list.get(i).getTNumber();
                            }
                        }
                        tv_u.setText(strU);
                        List<String> names = new ArrayList<>(); //折线名字集合
                        List<Integer> colour = new ArrayList<>();//折线颜色集合
                        //折线名字 //折线颜色
                        names.add("算力");
                        names.add("价钱");
                        colour.add(getResources().getColor(R.color.line_blue));
                        colour.add(getResources().getColor(R.color.line_orange));
                        dynamicLineChartManager2 = new DynamicLineChartDetailManager(mChart2, names, colour, 30, strU,strUU);
                        dynamicLineChartManager2.setDescription("");
                        dynamicLineChartManager2.setYAxis(max, 0, 6,maxx,0);
                        for (int i = 0; i < list.size(); i++) {
                            dynamicLineChartManager2.addEntry(list.get(i),i,list);
                        }

                    }

                }

                @Override
                public void onError(String msg) {
                    super.onError(msg);

                    loadingDialog.dismiss();

                }
            });
        }
        else
        {

            ToastUtil.showToast(HomeSecondDetailAc.this,getResources().getString(R.string.internet_error));
        }

    }
}
